import network
import utime as time
from modem import net
# from driver import RTC

# 联网状态标志
g_connect_status = False
Net = None
g_time_synced = False
# net_rtc = RTC()


def on_4g_cb(args):
    """4G网络状态回调函数"""
    global g_connect_status
    pdp = args[0]
    netwk_sta = args[1]
    if netwk_sta == 1:
        g_connect_status = True
    else:
        g_connect_status = False

def connect_network():
    """连接网络并同步时间"""
    global Net, g_connect_status
    try:
        # 初始化网络客户端
        Net = network.NetWorkClient()
        g_register_network = False
        # 检查网络注册状态
        if Net._stagecode is not None and Net._stagecode == 3 and  Net._subcode == 1:
            g_register_network = True
        else:
            g_register_network = False
        
        # 设置网络状态回调
        if g_register_network :
            Net.on(1, on_4g_cb)
            Net.connect(None)
        else:
            print('Network registered failed')
        
        while True:
            if g_connect_status:
                print('Network connection successed')
                break
            time.sleep_ms(20)

    except Exception as e:
        print('Network connection error: %s' % e)
        return False

def disconnect_network():
    """断开网络连接"""
    global Net, g_connect_status, g_time_synced
    
    try:
        if 'Net' in globals() and Net:
            Net.disconnect()
            print('Network disconnected')
        g_connect_status = False
        g_time_synced = False
    except Exception as e:
        print('Error disconnecting network: %s' % e)

def set_flight_mode(value):
    """
    设置飞行模式
    value =1 打开飞行模式
    value =0 关闭飞行模式
    """
    if value :
        net.setModem(value)
        ret = get_flight_mode()
        print("Flight mode enabled:",ret)
    else:
        net.setModem(value)
        print("Exit Flight mode ")
def get_flight_mode():
    """获取飞行模式状态"""
    return net.getModem()

def get_network_status():
    """获取网络连接状态"""
    return g_connect_status

def get_time_sync_status():
    """获取时间同步状态"""
    return g_time_synced

def get_network_info():
    """获取网络详细信息"""
    try:
        if 'Net' in globals() and Net and g_connect_status:
            return {
                'connected': g_connect_status,
                'time_synced': g_time_synced,
                'stagecode': Net._stagecode,
                'subcode': Net._subcode
            }
    except:
        pass
    
    return {
        'connected': False,
        'time_synced': False,
        'stagecode': None,
        'subcode': None
    }

# 保持向后兼容的函数名
def getNetFlag():
    """联网状态标志位（保持向后兼容）"""
    return get_network_status()